﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using MyVoteMVC.Common.Specifications;

namespace MyVoteMVC.Common.Extensions
{
    public static class SpecificationExtension
    {
        /*****************************
        * 引用地址:http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx
        * ****************************/
        public static Expression<T> Compose<T>(this Expression<T> left, Expression<T> right, Func<Expression, Expression, Expression> merge)
        {
            // build parameter map (from parameters of second to parameters of first)
            var map = left.Parameters.Select((f, i) => new { f, s = right.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

            // replace parameters in the second lambda expression with parameters from the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, right.Body);

            // apply composition of lambda expression bodies to parameters from the first expression 
            return Expression.Lambda<T>(merge(left.Body, secondBody), left.Parameters);
        }

        public static Expression<Func<TEntity, bool>> Not<TEntity>(this Expression<Func<TEntity, bool>> x) where TEntity : class
        {
            var result = Expression.Lambda<Func<TEntity, bool>>(Expression.Not(x.Body), x.Parameters);
            return result;
        }

        /// <summary>
        ///  两个ISpecification类型实例进行与操作
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        public static ISpecification<TEntity> And<TEntity>(this ISpecification<TEntity> s1, ISpecification<TEntity> s2) where TEntity : class
        {
            return new AndSpecification<TEntity>(s1, s2);
        }

        /// <summary>
        /// 两个ISpecification类型实例进行或操作
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        public static ISpecification<TEntity> Or<TEntity>(this ISpecification<TEntity> s1, ISpecification<TEntity> s2) where TEntity : class
        {
            return new OrSpecification<TEntity>(s1, s2);
        }

        /// <summary>
        ///  ISpecification类型实例进行非操作
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="x"></param>
        /// <returns></returns>
        public static ISpecification<TEntity> Not<TEntity>(this ISpecification<TEntity> x) where TEntity : class
        {
            return new NotSpecification<TEntity>(x);
        }
    }
}
